<template>
  <div>
    <el-form
      ref="dataFormRef"
      v-loading="loading"
      :model="state.form"
      :rules="dataRules"
      label-width="200px"
      label-position="top"
      :disabled="operType === 'view'"
    >
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="基准节点" prop="baseRunNodeId">
            <CommonSelect
              v-model:defaultValue="state.form.baseRunNodeId"
              :placeholder="translate('默认当前节点')"
              label="nodeName"
              value="id"
              :url="baseRunNodeListUrl"
              auto-query
              @change="handleBaseRunNodeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="基准节点办理人类型" prop="baseJobType">
            <el-tooltip placement="top">
              <template #content
                >>标识【待加签任务】基于某个节点下某个审批人或审批角色任务前后做加签</template
              >
              <el-radio-group
                v-model="state.form.baseJobType"
                @change="handleBaseUserOrRoleType"
              >
                <el-radio
                  v-for="(item, index) in DIC_PROP.JOB_USER_TYPE"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col v-if="state.form.baseJobType === '0'" :span="12" class="mb20">
          <el-form-item label="基准节点任务办理人" prop="baseUserId">
            <CommonSelect
              ref="handleUserIdRef"
              v-model:defaultValue="state.form.baseUserId"
              :placeholder="translate('默认当前任务审批人')"
              label="userName"
              value="id"
              :url="nodeUserListUrl"
              auto-query
            />
          </el-form-item>
        </el-col>
        <el-col v-if="state.form.baseJobType === '1'" :span="12" class="mb20">
          <el-form-item label="基准节点任务办理角色" prop="baseRoleId">
            <CommonSelect
              v-model:defaultValue="state.form.baseRoleId"
              :placeholder="translate('默认当前任务审批角色')"
              label="roleName"
              value="id"
              :url="nodeRoleListUrl"
              auto-query
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="加签任务办理人类型" prop="signJobType">
            <el-radio-group
              v-model="state.form.signJobType"
              @change="handleUserOrRoleType"
            >
              <el-radio
                v-for="(item, index) in DIC_PROP.JOB_USER_TYPE"
                :key="index"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="state.form.signJobType === '0'" :span="24" class="mb20">
          <el-form-item label="加签任务办理人" prop="handleUserId">
            <CommonSelect
              ref="handleUserIdRef"
              v-model:defaultValue="state.form.handleUserId"
              :placeholder="translate('请选择加签审批人')"
              expanding
              label="userName"
              value="id"
              url="/admin/sysuser/get/list"
              auto-query
            />
            <div style="margin-left: 10px; padding-left: 10px">
              <el-button type="primary" @click="showUserPicker"
                >其它人员</el-button
              >
              {{ state.form.handleUserName }}
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="state.form.signJobType === '1'" :span="24" class="mb20">
          <el-form-item label="加签任务办理角色" prop="handleRoleId">
            <CommonSelect
              v-model:defaultValue="state.form.handleRoleId"
              :placeholder="translate('请选择加签审批角色')"
              expanding
              label="roleName"
              value="id"
              url="/admin/role/get/list"
              auto-query
            />
            <div style="margin-left: 10px; padding-left: 10px">
              <el-button type="primary" @click="showRolePicker"
                >其它角色</el-button
              >
              {{ state.form.handleRoleName }}
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <footer class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button type="warning" icon="circle-close" @click="handleClose"
          >取消</el-button
        >
        <el-button type="primary" :loading="loading" @click="handleUpdate"
          >确认</el-button
        >
      </span>
    </footer>
    <StaffPicker ref="staffPickerRef" @change="handleStaffConfirm" />
    <RolePicker ref="rolePickerRef" @change="handleRoleConfirm" />
  </div>
</template>

<script setup lang="ts" name="JobSignature">
import { translate } from "@/plugins/i18n";
import { DIC_PROP } from "@/views/design/process/Dict";
import { useMessage } from "@/hooks/message";
import { ref, reactive, onMounted, watch, computed } from "vue";
import CommonSelect from "@/components/commonSelect.vue";
import * as doJob from "@/api/flow/task/index";

const props = defineProps({
  id: {
    type: String,
    default: "",
    required: true
  },
  flowInstId: {
    type: String,
    default: "",
    required: true
  },
  runNodeId: {
    type: String,
    default: "",
    required: true
  },
  signedType: {
    type: String,
    default: "",
    required: true
  },
  currJob: {
    default: null
  }
});

const $message = useMessage();
const $emit = defineEmits(["success", "closed"]);
// 定义变量内容
const dataFormRef = ref();
const loading = ref(false);
const operType = ref("");
const staffPickerRef = ref(null);
const rolePickerRef = ref(null);

// 提交表单数据
const state = reactive({
  form: {
    flowInstId: "",
    baseJobType: "0",
    signJobType: "",
    baseRunNodeId: "",
    baseUserId: "",
    baseRoleId: "",
    handleUserId: "",
    handleUserName: "",
    handleRoleId: "",
    handleRoleName: ""
  }
});

// 定义校验规则
const dataRules = ref({
  flowInstId: [
    { required: true, message: "流程实例ID不能为空", trigger: "blur" }
  ],
  baseRunNodeId: [
    { required: true, message: "基于该节点加签不能为空", trigger: "blur" }
  ],
  baseJobType: [
    { required: true, message: "基于任务类型不能为空", trigger: "blur" }
  ],
  signJobType: [
    { required: true, message: "加签任务类型不能为空", trigger: "blur" }
  ]
});

const baseRunNodeListUrl = computed(() => {
  return `/esflow/run/node/list/${props.currJob.flowInstId}`;
});

const nodeUserListUrl = computed(() => {
  return `/esflow/run/job/list/user/${state.form.baseRunNodeId}`;
});

const nodeRoleListUrl = computed(() => {
  return `/esflow/run/job/list/role/${state.form.baseRunNodeId}`;
});

const showUserPicker = () => {
  staffPickerRef.value.show();
};

const showRolePicker = () => {
  rolePickerRef.value.show();
};

const handleStaffConfirm = rows => {
  state.form.handleUserId = rows[0].id;
  state.form.handleUserName = rows[0].userName;
};

const handleRoleConfirm = rows => {
  state.form.handleRoleId = rows[0].id;
  state.form.handleRoleName = rows[0].roleName;
};

const handleBaseRunNodeChange = val => {
  state.form.baseRunNodeId = val;
};

function initJobData() {
  state.form.baseRunNodeId = props.runNodeId;
}

function handleBaseUserOrRoleType(type) {
  if (type === DIC_PROP.JOB_USER_TYPE[0].value) {
    state.form.baseRoleId = "";
  } else if (type === DIC_PROP.JOB_USER_TYPE[1].value) {
    state.form.baseUserId = "";
  }
}

function handleUserOrRoleType(type) {
  if (type === DIC_PROP.JOB_USER_TYPE[0].value) {
    state.form.handleRoleId = "";
  } else if (type === DIC_PROP.JOB_USER_TYPE[1].value) {
    state.form.handleUserId = "";
  }
}

const handleClose = () => {
  $emit("closed");
};

async function handleUpdate() {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  // 基于节点下该审批人/角色
  if (state.form.baseJobType === DIC_PROP.JOB_USER_TYPE[0].value) {
    if (!state.form.baseUserId) {
      $message.warning("基准节点任务办理人不能为空");
      return;
    }
  } else if (state.form.baseJobType === DIC_PROP.JOB_USER_TYPE[1].value) {
    if (!state.form.baseRoleId) {
      $message.warning("基准节点任务办理角色不能为空");
      return;
    }
  }
  // 指定加签审批人/角色
  if (state.form.signJobType === DIC_PROP.JOB_USER_TYPE[0].value) {
    if (!state.form.handleUserId) {
      $message.warning("加签任务办理人不能为空");
      return;
    }
  } else if (state.form.signJobType === DIC_PROP.JOB_USER_TYPE[1].value) {
    if (!state.form.handleRoleId) {
      $message.warning("加签任务办理角色不能为空");
      return;
    }
  }
  loading.value = true;
  try {
    const params = {
      id: props.id,
      runNodeId: props.runNodeId,
      signedType: props.signedType,
      baseRunNodeId: state.form.baseRunNodeId,
      baseRoleId: state.form.baseRoleId,
      baseUserId: state.form.baseUserId,
      handleUserId: state.form.handleUserId,
      handleRoleId: state.form.handleRoleId
    };
    doJob.signature(params).then(res => {
      if (res.code === 200) {
        useMessage().success("加签成功");
        $emit("success", state.form);
      } else {
        useMessage().error(res.msg);
      }
    });

    setTimeout(() => {
      // 异步异常
      loading.value = false;
    }, 3000);
  } catch (e) {
    loading.value = false;
  }
}

// 监听双向绑定
watch(
  () => props.id,
  val => {
    initJobData();
  }
);

onMounted(() => {
  initJobData();
});
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  text-align: center;

  .dialog-footer {
    text-align: center;
  }
}
</style>
